﻿using System;
using System.Net.Sockets;
using System.Text;
using AccelerateSensor.Console.Tools;

namespace AccelerateSensor.Console
{
    public class SendMsgHelper
    {
        /// <summary>
        /// 发送心跳
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        public void SendHeartbeat(Socket socket)
        {
            if (socket == null || !socket.Connected)
            {
                return;
            }

            var buffer = BitConverter.GetBytes(Constants.HeartbeatString.Length);
            Array.Reverse(buffer);
            var dataNum = socket.Send(buffer, 4, SocketFlags.None);
            if (dataNum < 4)
            {
                System.Console.WriteLine("SendHeartbeat length failed");
                return;
            }

            buffer = Encoding.UTF8.GetBytes(Constants.HeartbeatString);
            dataNum = socket.Send(buffer, buffer.Length, SocketFlags.None);
            if (dataNum < buffer.Length)
            {
                System.Console.WriteLine("SendHeartbeat json failed");
                return;
            }

            System.Console.WriteLine("======================= Send heartbeat back ========================");

            return;
        }
    }
}
